﻿using aichat.Data;
using aichat.Entities;
using aichat.Share;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace aichat.Services
{
    public class UserService : IUserService
    {
        private readonly ApplicationDbContext _context;

        public UserService(ApplicationDbContext context)
        {
            _context = context;
        }

        public int AddUser(UserModel user)
        {
            int nRet = 0;
            try
            {
                _context.Users.Add(user);
                nRet = _context.SaveChanges();
            }
            catch (Exception ex)
            {

            }
            return nRet;    
        }

        public int DeleteUser(int userId)
        {
            int nRet = 0;
            try
            {
                var user = _context.Users.FirstOrDefault(u => u.UserId == userId);
                if (user != null)
                {
                    _context.Users.Remove(user);
                    nRet = _context.SaveChanges();
                }
            }
            catch (Exception ex)
            {

            }
            return nRet;
        }

        public int EditUser(UserModel user)
        {
            int nRet = 0;
            try
            {
                _context.Users.Update(user);
                nRet = _context.SaveChanges();
            }
            catch (Exception ex)
            {

            }
            return nRet;
        }

        public List<UserModel> FindAllUser()
        {
            List<UserModel> data = new List<UserModel>();
            try
            {
                data = _context.Users.ToList();
            }
            catch (Exception ex)
            {
                
            }
            return data;
        }

        public async Task<UserModel?> GetUserByIdAsync(int id)
        {
            return await _context.Users.FindAsync(id);
        }

        public async Task<UserModel?> GetUserByUsernameAsync(string username)
        {
            return await _context.Users.FirstOrDefaultAsync(u => u.UserName == username);
        }

        public async Task<UserModel?> GetUserByEmailAsync(string email)
        {
            return await _context.Users.FirstOrDefaultAsync(u => u.Email == email);
        }

        public async Task<bool> CreateUserAsync(UserModel user)
        {
            try
            {
                user.Password = PasswordHelper.HashPassword(user.Password ?? "");
                _context.Users.Add(user);
                await _context.SaveChangesAsync();
                return true;
            }
            catch
            {
                return false;
            }
        }

        public async Task<bool> UpdateUserAsync(UserModel user)
        {
            try
            {
                _context.Users.Update(user);
                await _context.SaveChangesAsync();
                return true;
            }
            catch
            {
                return false;
            }
        }

        public async Task<bool> DeleteUserAsync(int id)
        {
            try
            {
                var user = await _context.Users.FindAsync(id);
                if (user != null)
                {
                    _context.Users.Remove(user);
                    await _context.SaveChangesAsync();
                    return true;
                }
                return false;
            }
            catch
            {
                return false;
            }
        }

        public async Task<bool> ValidateUserAsync(string username, string password)
        {
            var user = await _context.Users.FirstOrDefaultAsync(u => u.UserName == username);
            if (user != null)
            {
                var isValid = PasswordHelper.VerifyPassword(password, user.Password ?? "");
                if (isValid)
                {
                    user.LastLoginAt = DateTime.Now;
                    await _context.SaveChangesAsync();
                }
                return isValid;
            }
            return false;
        }

        public async Task<bool> IsVipUserAsync(int userId)
        {
            var user = await _context.Users.FindAsync(userId);
            if (user == null) return false;

            if (user.VipType == VipType.Permanent) return true;
            if (user.VipType == VipType.None) return false;

            return user.VipExpireDate.HasValue && user.VipExpireDate.Value > DateTime.Now;
        }

        public async Task<bool> CanUserChatAsync(int userId)
        {
            var user = await _context.Users.FindAsync(userId);
            if (user == null) return false;

            // VIP用户无限制
            if (await IsVipUserAsync(userId)) return true;

            // 检查是否是新的聊天日期
            if (user.LastChatDate.Date != DateTime.Today)
            {
                user.DailyChatCount = 0;
                user.LastChatDate = DateTime.Today;
                await _context.SaveChangesAsync();
            }

            // 非VIP用户每天限制20次
            return user.DailyChatCount < 20;
        }

        public async Task<bool> IncrementChatCountAsync(int userId)
        {
            var user = await _context.Users.FindAsync(userId);
            if (user == null) return false;

            if (user.LastChatDate.Date != DateTime.Today)
            {
                user.DailyChatCount = 1;
                user.LastChatDate = DateTime.Today;
            }
            else
            {
                user.DailyChatCount++;
            }

            await _context.SaveChangesAsync();
            return true;
        }

        public async Task<List<UserModel>> GetAllUsersAsync()
        {
            return await _context.Users.ToListAsync();
        }

        public async Task<bool> UpdateVipStatusAsync(int userId, VipType vipType, DateTime? expireDate)
        {
            var user = await _context.Users.FindAsync(userId);
            if (user == null) return false;

            user.VipType = vipType;
            user.VipExpireDate = expireDate;
            user.IsVip = vipType != VipType.None;

            await _context.SaveChangesAsync();
            return true;
        }

        public UserModel Login(string userName, string password, bool IsChecked)
        {
            return _context.Users.FirstOrDefault(u => u.UserName == userName && u.Password == password);
        }
    }
}
